#include "ServiceTaskmanager.h"
#include "Task.h"
#include "TaskInstallapp.h"
#include "TaskUninstallapp.h"
#include "TaskExportapp.h"

namespace Gnodroid {

    ServiceTaskmanager::ServiceTaskmanager() :
        Service(SERVICE_TASKMANAGER)
    {}

    void
    ServiceTaskmanager::start()
    {}


    void
    ServiceTaskmanager::stop()
    {}

    Task*
    ServiceTaskmanager::getTaskById(long id)
    {
        for (Task* t : m_lsTask) {
            if (t->getId() == id) {
                t->ref();
                return t;
            }
        }
        return nullptr;
    }

    sigc::signal<void, long>
    ServiceTaskmanager::signalTaskAdded()
    {
        return m_signalTaskAdded;
    }


    long
    ServiceTaskmanager::taskInstallApp(std::string apkPath)
    {
        Task* t = new TaskInstallapp(apkPath);
        m_lsTask.push_back(t);

        t->signal_state_changed().connect(sigc::mem_fun(*this, &ServiceTaskmanager::__finishTask));

        signalTaskAdded().emit(t->getId());

        t->start();

        return t->getId();
    }

    long
    ServiceTaskmanager::taskUninstallApp(std::string appPid)
    {
        Task* t = new TaskUninstallapp(appPid);
        m_lsTask.push_back(t);

        t->signal_state_changed().connect(sigc::mem_fun(*this, &ServiceTaskmanager::__finishTask));

        signalTaskAdded().emit(t->getId());
        t->start();
        return t->getId();
    }

    long
    ServiceTaskmanager::taskExportApp(std::string appPid, std::string destPath)
    {
        Task* t = new TaskExportapp(appPid, destPath);
        m_lsTask.push_back(t);

        t->signal_state_changed().connect(sigc::mem_fun(*this, &ServiceTaskmanager::__finishTask));

        signalTaskAdded().emit(t->getId());
        t->start();
        return t->getId();
    }

    void
    ServiceTaskmanager::__finishTask(long id, TaskState state)
    {
        if (state == TaskState::ERROR
                || state == TaskState::BREAK
                || state == TaskState::FINNISHED) {
            Task* t = getTaskById(id);
            m_lsTask.remove(t);
            t->unref();     //减少获取任务增加的引用
            t->unref();     //减少任务管理器持有的引用
            return;
        }
        return;

    }
}
